<?php

namespace App\Http\Controllers\Api\Record;

use App\Http\Controllers\ApiController;
use App\Models\DrugDictionary;
use App\Models\MedicalComplaint;
use Illuminate\Http\Request;

class ComplaintController extends ApiController
{
    public function show(Request $request)
    {
        $data      = null;
        $record_id = $request->get('record_id');

        if ($record_id > 0) {

            $data = MedicalComplaint::select(['id', 'symptoms', 'medication'])
                                    ->where(['record_id' => $record_id])->first();
        } else {
            abort(400, '缺失病历ID');
        }
        if (is_null($data)) {
            return $this->hasNoData();
        }

        if (!empty($data->medication)) {
            $names = collect($data->medication)->pluck('name');

            if ($names->count()) {
                $drugs = DrugDictionary::select(['name', 'is_insulin'])
                                       ->whereIn('name', $names)
                                       ->groupBy('name')
                                       ->get()->pluck('is_insulin', 'name');

                $data->medication = collect($data->medication)->map(function ($medication) use ($drugs) {
                    $medication['is_insulin'] = $drugs->get($medication['name']);

                    return $medication;
                });
            }
        }

        return $this->response($data->toArray());
    }
}
